package org.moyakarta.rest;

import java.util.Collection;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

public class PlaceStorage {

   public synchronized String generateId() {
      String id = generateEncodedId();
      while (getPlace(id) != null) {
         id = generateEncodedId();
      }
      return id;
   }

   private static String generateEncodedId() {
      Integer intRandom = new Integer(0);
      while (intRandom.intValue() == 0l) {
         intRandom = new Random().nextInt();
         if (Integer.signum(intRandom) < 0)
            intRandom = -intRandom;
      }
      String result = base48Encode(Long.valueOf(String.valueOf(intRandom)));
      return result;
   }

   private static String base48Encode(Long number) {
      Double num = Double.valueOf(number);
      String charSet = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
      Integer length = charSet.length();
      String encodeString = new String();
      while (num >= length) {
         int index = Integer.parseInt(String.valueOf(num.longValue() % length)); // Long
         // value
         // to
         // int
         // value
         encodeString = charSet.charAt(index) + encodeString;
         num = Math.ceil(new Double(num / length) - 1);
      }
      encodeString = charSet.charAt(num.intValue()) + encodeString;

      return encodeString;
   }

   private Map<String, Place> places = new ConcurrentHashMap<String, Place>();

   public PlaceStorage() {
      init();
   }

   private void init() {
      Place place = new Place();
      place.setTitle("JUnit in Action");
      place
            .setLink("http://moyakarta.com/maps/yandex-maps.html?"
                  + "lat=49.44402965123416&lng=32.058283332735314&z=13&t=map&w=500px&h=300px");
      place.setLat(49.44402965123416);
      place.setLon(32.058283332735314);
      place.setZ(13);
      putPlace(place);
   }

   public Place getPlace(String id) {
      return places.get(id);
   }

   public String putPlace(Place place) {
      String id = place.getId();
      if (id == null || id.trim().length() == 0) {
         id = generateId();
         place.setId(id);
      }
      places.put(id, place);
      return id;
   }

   public Collection<Place> getAll() {
      return places.values();
   }

   public int numberOfPlaces() {
      return places.size();
   }
}
